/*
 * @File name: 非流式
 * @Author: 1079161148@qq.com
 * @Version: V1.0
 * @Date: 2025-03-03 17:13:18
 * @Description:
 * Copyright (C) 2024-{year} Tsing Micro Technology Inc All rights reserved.
 */
import express from 'express'
import bodyParser from 'body-parser'
import cors from 'cors'
import dotenv from 'dotenv'
import OpenAI from 'openai'

// 确保在应用开始时加载环境变量
dotenv.config()

// 验证环境变量是否正确加载
console.log('API Key:', process.env.DEEPSEEK_API_KEY ? '已配置' : '未配置')

const app = express()
const PORT = process.env.PORT || 8080

// 中间件配置
app.use(cors())
app.use(bodyParser.json())

// 创建 OpenAI 实例
const openai = new OpenAI({
  apiKey: 'sk-376d67ae642e4034aec75a21200f5cee',
  baseURL: 'https://api.deepseek.com/v1', // 添加 /v1 路径
  defaultHeaders: {
    'Content-Type': 'application/json',
  },
  defaultQuery: undefined,
  organization: undefined,
  timeout: 30000,
  httpAgent: undefined,
  maxRetries: 2,
})

// 处理 DeepSeek 请求
app.post('/api/deepseek', async (req, res) => {
  try {
    console.log('Received request body:', req.body)

    // 设置响应头，支持流式传输
    res.setHeader('Content-Type', 'text/event-stream')
    res.setHeader('Cache-Control', 'no-cache')
    res.setHeader('Connection', 'keep-alive')

    const completion = await openai.chat.completions.create({
      model: 'deepseek-chat',
      messages: [
        {
          role: 'system',
          content: '你是一个有帮助的AI助手。',
        },
        ...req.body.messages,
      ],
      temperature: 0.7,
      max_tokens: 1000,
      top_p: 0.95,
      frequency_penalty: 0,
      presence_penalty: 0,
      stream: true, // 启用流式响应
    })

    for await (const chunk of completion) {
      const content = chunk.choices[0]?.delta?.content || ''
      if (content) {
        res.write(`data: ${JSON.stringify({ content })}\n\n`)
      }
    }

    res.write('data: [DONE]\n\n')
    res.end()
  } catch (error) {
    console.error('API Error:', {
      name: error.name,
      status: error.status,
      message: error.message,
      type: error.type,
    })

    res.write(
      `data: ${JSON.stringify({
        error: true,
        message: error.message,
      })}\n\n`,
    )
    res.end()
  }
})

// 测试路由
app.get('/api/test', (req, res) => {
  res.json({ message: 'Server is working!' })
})

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`)
})
